from AlphaPoseService import alphapose_return_coordinate_and_scores, alphapose_return_image, prepare_model
from Utils import base64_to_image, image_to_base64, tensor_to_list, tensor_to_str
import web
import os, sys, random, traceback
import json
import base64
import traceback
import datetime, time
import numpy as np
import cv2

det_model, pose_model = prepare_model()

urls = (
    '/', 'index',
)

render = web.template.render('templates/')


class index:

    # def POST(self):
    #     data = json.loads(web.data())
    #     data_json = json.loads(data)
    #     value = data_json.get('image')
    #     tmp_image = base64_to_image(value)
    #     image = alphapose_return_image(det_model, pose_model, tmp_image)
    #     image_string = image_to_base64(image)
    #     return image_string

    def POST(self):
        web.header('content-type', 'text/json')
        data = json.loads(web.data())
        data_json = json.loads(data)
        value = data_json.get('image')
        tmp_image = base64_to_image(value)
        result = alphapose_return_coordinate_and_scores(det_model, pose_model, tmp_image)
        print(result)
        if result is None:
            return None
        else:
            print(result)
            d = {}
            i = 0
            for human in result:
                human['keypoints'] = tensor_to_list(human['keypoints'])
                human['kp_score'] = tensor_to_list(human['kp_score'])
                human['proposal_score'] = tensor_to_list(human['proposal_score'])
                d['human'+str(i)] = human
                i += 1
            return json.dumps(d)


if __name__ == "__main__":
    app = web.application(urls, globals())
    web.banitch_size = 1
    app.run()
